package com.ruoyi.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Properties;

/**
 * @author WangYaDong
 * @date 2022/8/31 14:31
 * @descripyion
 */
public class URLUtil {
    public static Logger LOG= LoggerFactory.getLogger(URLUtil.class);

    public static String sendPOSTRequest(String url, MultiValueMap<String, String> params) {
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, headers);
        // 执行HTTP请求，将返回的结构使用String类格式化
        ResponseEntity<String> response = client.exchange(url, method, requestEntity, String.class);
        return response.getBody();
    }



    /**
     * post方式请求http服务
     * @param urlStr
     * @param params   name=yxd&age=25
     * @return
     * @throws Exception
     */
    public  String getURLTickerByPost(String urlStr,String params,String token)throws Exception{
        StringBuilder sb = new StringBuilder();
        try {
//            System.setProperty("https.proxyHost","127.0.0.1");
//            System.setProperty("https.proxyHost","10.102.8.28");
            Properties properties = System.getProperties();

//            System.setProperty("https.proxyHost",null);
            System.setProperty("https.proxyHost","");

            String proxyHost = System.getProperty("https.proxyHost");
            SslUtils.ignoreSsl();
            URL url = new URL(urlStr);
//        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1",9091));
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("API-TOKEN", token);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("Content-Length", "<calculated when request is sent>");
            conn.setRequestProperty("Host", "<calculated when request is sent>");
            conn.setRequestProperty("User-Agent", "PostmanRuntime/7.26.8");
            conn.setRequestProperty("Accept", "*/*");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
            conn.setRequestProperty("Connection", "keep-alive");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
            printWriter.write(params);
            printWriter.flush();
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String str = null;
                while ((str = in.readLine()) != null) {
                    sb.append(str);
                }
            } catch (Exception ex) {
                throw ex;
            } finally {
                try {
                    conn.disconnect();
                    if (in != null) {
                        in.close();
                    }
                    if (printWriter != null) {
                        printWriter.close();
                    }
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }catch (Exception e){

        }finally {
        }
        return sb.toString();
    }




//    private static Properties reqProperties = PropertyUtil.getFileInstance("/req.properties");
    /**
     * 程序中访问http数据接口
     */
    public static String getURLContent(String urlStr) {
        /** 网络的url地址 */
        URL url = null;
        /** http连接 */
        HttpURLConnection httpConn = null;

        /**//** 输入流 */
        BufferedReader in = null;
        StringBuffer sb = new StringBuffer();
        try{
            url = new URL(urlStr);
            in = new BufferedReader( new InputStreamReader(url.openStream(),"UTF-8") );
            String str = null;
            while((str = in.readLine()) != null) {
                sb.append( str );
            }
        } catch (Exception ex) {

        } finally{
            try{
                if(in!=null) {
                    in.close();
                }
            }catch(IOException ex) {
            }
        }
        String result =sb.toString();
        System.out.println(result);
        return result;
    }
    public static String sendByPost(String urlStr,String params)throws Exception{
        LOG.info("开始尝试连接URL:{}",urlStr);
        LOG.info("上送参数:{}",params);

        SslUtils.ignoreSsl();
        URL url=new URL(urlStr);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type","application/json");
        conn.setRequestProperty("Content-Length","<calculated when request is sent>");
        conn.setRequestProperty("Host","<calculated when request is sent>");
        conn.setRequestProperty("User-Agent","PostmanRuntime/7.26.8");
        conn.setRequestProperty("Accept","*/*");
        conn.setRequestProperty("Accept-Encoding","gzip, deflate, br");
        conn.setRequestProperty("Connection","keep-alive");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
        printWriter.write(params);
        printWriter.flush();
        BufferedReader in = null;
        StringBuilder sb = new StringBuilder();
        try{
            in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8") );
            String str = null;
            while((str = in.readLine()) != null) {
                sb.append( str );
            }
        } catch (Exception ex) {
            LOG.info("连接API异常");
            //更新下游通知表（先删除当天的通知数据，再插入）
            throw ex;
        } finally{
            try{
                conn.disconnect();
                if(in!=null){
                    in.close();
                }
                if(printWriter!=null){
                    printWriter.close();
                }
            }catch(IOException ex) {
                throw ex;
            }
        }
        LOG.info("返回参数:{}",sb.toString());
        return sb.toString();
    }

    public static String sendByGet(String urlStr)throws Exception{
        LOG.info("开始尝试连接URL:{}",urlStr);

        SslUtils.ignoreSsl();
        URL url=new URL(urlStr);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-Type","application/json");
        conn.setRequestProperty("Content-Length","<calculated when request is sent>");
        conn.setRequestProperty("Host","<calculated when request is sent>");
        conn.setRequestProperty("User-Agent","PostmanRuntime/7.26.8");
        conn.setRequestProperty("Accept","*/*");
        conn.setRequestProperty("Accept-Encoding","gzip, deflate, br");
        conn.setRequestProperty("Connection","keep-alive");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        PrintWriter printWriter = new PrintWriter(conn.getOutputStream());
        printWriter.flush();
        BufferedReader in = null;
        StringBuilder sb = new StringBuilder();
        try{
            in = new BufferedReader( new InputStreamReader(conn.getInputStream(),"UTF-8") );
            String str = null;
            while((str = in.readLine()) != null) {
                sb.append( str );
            }
        } catch (Exception ex) {
            LOG.info("连接API异常");
            //更新下游通知表（先删除当天的通知数据，再插入）
            throw ex;
        } finally{
            try{
                conn.disconnect();
                if(in!=null){
                    in.close();
                }
                if(printWriter!=null){
                    printWriter.close();
                }
            }catch(IOException ex) {
                throw ex;
            }
        }
        LOG.info("返回参数:{}",sb.toString());
        return sb.toString();
    }


}
